package service

import (
	"context"
	"disk/disk_rpc_server/disk_pb"
	"disk/utils/mysql"
	"gorm.io/gorm"
)

func (*GrpcServer) Update(ctx context.Context, req *disk_pb.UpdateReq) (resp *disk_pb.UpdateResp, err error) {
	db := Database.Session(&gorm.Session{NewDB: true})
	var dataList []mysql.DiskList
	var resultList []*disk_pb.DiskList
	id := req.GetId()

	var tmpDataList []mysql.DiskList
	result := db.Where("`id` = ?", id).Find(&tmpDataList)
	if result.Error != nil {
		return &disk_pb.UpdateResp{
			Code:    1,
			Message: result.Error.Error(),
		}, nil
	}

	if len(tmpDataList) == 0 {
		return &disk_pb.UpdateResp{
			Code:    1,
			Message: "更新失败，数据不存在",
		}, nil
	} else {
		resultList = append(resultList, req.List)
		mysql.DiskListRpcToOrm(resultList, &dataList)
		dataList[0].ID = uint(id)
		result := db.Where("`id` = ?", id).Updates(&dataList[0])
		if result.RowsAffected == 0 {
			return &disk_pb.UpdateResp{
				Code:    1,
				Message: "更新失败",
			}, nil
		} else if result.Error != nil {
			return &disk_pb.UpdateResp{
				Code:    1,
				Message: "更新失败:" + result.Error.Error(),
			}, nil
		} else {
			return &disk_pb.UpdateResp{
				Code:    0,
				Message: "更新成功",
			}, nil
		}
	}
}
